# -*-coding:utf-8 -*-
# @Time: 2023/2/20 0020 下午 14:33
# @Author: Cwoner
# @Organization: CTIM
# @Software: PyCharm


import requests
from lxml import etree
import hashlib
from setting import SAVEPATH
import os
import re

from tools.serverAPI import upload_file

class GongRenShiBao():
    def __init__(self,ccdate,id=''):#20230101
        self.url = f'http://www.xjzgh.org.cn/ghyw/grsb/grsb.htm'
        self.ccdate = f'{ccdate[:4]}年{ccdate[4:6]}月{ccdate[6:8]}日'
        self.id = id
        self.name = '工人时报（汉）'
        print('初始化：',self.name, self.url)
        self.mid = hashlib.md5((self.name+'_baozi').encode()).hexdigest()
        if not os.path.isdir(SAVEPATH+self.mid):
            os.mkdir(SAVEPATH+self.mid)

    def index(self):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh,zh-CN;q=0.9",
            "Cache-Control": "no-cache",
            "Pragma": "no-cache",
            "Proxy-Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
        }
        url = "http://www.xjzgh.org.cn/ghyw/grsb/grsb.htm"
        response = requests.get(url, headers=headers,  verify=False)
        if response.status_code == 200:
            text = response.content.decode()
            html = etree.HTML(text)
            xpath = f'//a[contains(text(),"{self.ccdate}")]/@href'
            try:
                surl = html.xpath(xpath)[0]
            except:
                return
            rid = re.search('id=(\d+)',surl).group(1)
            return rid


    def get_imgs(self,rid):
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh,zh-CN;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Referer": "https://www.founderfx.cn/elecPublish/index.html",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
        url = "https://www.founderfx.cn/ebook/epaper/getDaYangByEpaperId"
        params = {
            "id": rid,
            "module": "ebook"
        }
        response = requests.get(url, headers=headers, params=params)
        if response.status_code == 200:
            try:
                data = response.json()['data']
            except:
                return
            x = 1
            for item in data:
                picFile = item['picFile']
                tid = hashlib.md5((self.name + picFile + self.ccdate).encode()).hexdigest()
                file = tid + f'.{picFile.split(".")[-1]}'
                self.__download(file,picFile,f'未知{x}',tid)
                x += 1





    def __download(self,file,url,title,tid):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
        }
        response = requests.get(url, headers=headers, verify=False)
        if response.status_code == 200:
            path = SAVEPATH + self.mid + '/' + self.ccdate + '/'
            if not os.path.isdir(path):
                os.mkdir(path)
            with open(path + file,'wb',) as f:
                f.write(response.content)
            data = {
                'entity_id': self.mid,
                'title': title,
                'tid': tid,
                'file_name': file,
                'origin_url': url,
                'ndate': self.ccdate[:4] + '-' + self.ccdate[4:6] + '-' + self.ccdate[6:]
            }
            upload_file(data, response.content)


    def run(self):
        rid = self.index()







if __name__ == '__main__':
    ccdate = '20240306'
    hr = GongRenShiBao(ccdate)
    hr.run()



